<template>
  <div class="app-container">
    <!-- 添加通知按钮 -->
    <el-button type="primary" @click="showAddDialog">添加通知</el-button>

    <!-- 通知列表 -->
    <el-table :data="notifications" style="width: 100%">
      <el-table-column prop="title" label="通知标题"></el-table-column>
      <el-table-column prop="content" label="通知内容" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="notificationType" label="通知类型" :formatter="formatType"></el-table-column>
      <el-table-column prop="senderId" label="发送者" :formatter="formatSender"></el-table-column>
      <el-table-column prop="receiverType" label="接收类型" :formatter="formatReceiverType"></el-table-column>
      <el-table-column prop="receiverId" label="接收者ID"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" :formatter="formatDate"></el-table-column>
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewDetail(scope.row.id)">查看详情</el-button>
          <el-button size="mini" type="warning" @click="showUpdateStatusDialog(scope.row.id, scope.row.notificationType)">更新类型</el-button>
          <el-button size="mini" type="danger" @click="deleteNotification(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加通知对话框 -->
    <el-dialog :visible.sync="addDialogVisible" title="添加通知" width="50%">
      <el-form :model="newNotification" label-width="100px" :rules="rules" ref="notificationForm">
        <el-form-item label="通知标题" prop="title" required>
          <el-input v-model="newNotification.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="通知内容" prop="content" required>
          <el-input type="textarea" v-model="newNotification.content" :rows="4" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="通知类型" prop="notificationType" required>
          <el-select v-model="newNotification.notificationType" placeholder="请选择类型" style="width:100%">
            <el-option label="系统通知" :value="1"></el-option>
            <el-option label="班级通知" :value="2"></el-option>
            <el-option label="部门通知" :value="3"></el-option>
            <el-option label="个人通知" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送者" prop="senderId" required>
          <el-select v-model="newNotification.senderId" placeholder="请选择发送者" style="width:100%">
            <el-option
              v-for="item in senderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接收者类型" prop="receiverType" required>
          <el-select
            v-model="newNotification.receiverType"
            placeholder="请选择接收者类型"
            style="width:100%"
            @change="handleReceiverTypeChange">
            <el-option
              v-for="item in receiverTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接收者ID" prop="receiverId" required>
          <el-input
            v-model="newNotification.receiverId"
            placeholder="请输入接收者ID"
            type="number"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNotification">确定</el-button>
      </div>
    </el-dialog>

    <!-- 更新通知类型对话框 -->
    <el-dialog :visible.sync="updateStatusDialogVisible" title="更新通知类型" width="40%">
      <el-form :model="updateStatusForm" label-width="100px">
        <el-form-item label="当前通知ID">
          <el-input v-model="updateStatusForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="通知类型" prop="notificationType" required>
          <el-select v-model="updateStatusForm.notificationType" placeholder="请选择类型" style="width:100%">
            <el-option label="系统通知" :value="1"></el-option>
            <el-option label="班级通知" :value="2"></el-option>
            <el-option label="部门通知" :value="3"></el-option>
            <el-option label="个人通知" :value="4"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateStatusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUpdateStatus">确定</el-button>
      </div>
    </el-dialog>

    <!-- 通知详情对话框 -->
    <el-dialog :visible.sync="detailDialogVisible" title="通知详情" width="60%">
      <el-descriptions :column="1" border v-if="currentNotification">
        <el-descriptions-item label="通知标题">
          <span class="detail-label">通知标题：</span>{{ currentNotification.title || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="通知内容">
          <div>
            <div class="detail-label">通知内容：</div>
            <div class="content-box">{{ currentNotification.content || '无内容' }}</div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="通知类型">
          <span class="detail-label">通知类型：</span>
          {{ formatType({ notificationType: currentNotification.notificationType }) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="发送者">
          <span class="detail-label">发送者：</span>
          {{ formatSender({ senderId: currentNotification.senderId }) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="接收类型">
          <span class="detail-label">接收者类型：</span>
          {{ formatReceiverType(currentNotification.receiverType) || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="接收者">
          <span class="detail-label">接收者ID：</span>{{ currentNotification.receiverId || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="通知状态">
          <span class="detail-label">当前状态：</span>
          {{ formatStatus(currentNotification.status) || '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          <span class="detail-label">创建时间：</span>
          {{ formatDate(currentNotification.createTime) || '无记录' }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          <span class="detail-label">最后更新：</span>
          {{ formatDate(currentNotification.updateTime) || '无更新' }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getNotificationList,
  getNotificationDetail,
  addNotification,
  updateNotificationStatus,
  deleteNotification
} from '@/api/notification'

export default {
  data() {
    return {
      notifications: [],
      addDialogVisible: false,
      newNotification: {
        title: '',
        content: '',
        notificationType: null,
        senderId: null,
        receiverType: null,
        receiverId: null,
        status: 1
      },
      updateStatusDialogVisible: false,
      updateStatusForm: {
        id: null,
        notificationType: null
      },
      detailDialogVisible: false,
      currentNotification: null,

      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入通知标题', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入通知内容', trigger: 'blur' }
        ],
        notificationType: [
          { required: true, message: '请选择通知类型', trigger: 'change' }
        ],
        senderId: [
          { required: true, message: '请选择发送者', trigger: 'change' }
        ],
        receiverType: [
          { required: true, message: '请选择接收者类型', trigger: 'change' }
        ],
        receiverId: [
          { required: true, message: '请输入接收者ID', trigger: 'blur' },
          { type: 'number', message: '接收者ID必须为数字', trigger: 'blur', transform: value => Number(value) }
        ]
      },

      // 下拉选项数据
      senderOptions: [
        { value: 1, label: '系统管理员' },
        { value: 2, label: '教务处' },
        { value: 3, label: '学生处' }
        // 实际项目中应该从API获取
      ],
      receiverTypeOptions: [
        { value: 1, label: '学生' },
        { value: 2, label: '班级' },
        { value: 3, label: '部门' },
        { value: 4, label: '员工' },
        { value: 5, label: '用户' }
      ]
    }
  },
  mounted() {
    this.fetchNotifications()
  },
  methods: {
    fetchNotifications() {
      getNotificationList().then(response => {
        this.notifications = response.data.data || []
      }).catch(error => {
        console.error('获取通知列表失败', error)
        this.$message.error('获取通知列表失败')
      })
    },
    viewDetail(id) {
      getNotificationDetail(id).then(response => {
        if (response.data.code === 1) {
          this.currentNotification = response.data.data
          this.detailDialogVisible = true
        } else {
          this.$message.error(response.data.msg || '获取详情失败')
        }
      }).catch(error => {
        console.error('获取通知详情失败', error)
        this.$message.error('获取详情失败')
      })
    },
    showAddDialog() {
      this.addDialogVisible = true
      this.$nextTick(() => {
        this.$refs.notificationForm?.clearValidate()
      })
    },
    saveNotification() {
      this.$refs.notificationForm.validate(valid => {
        if (!valid) {
          return false
        }

        // 确保receiverId是数字
        const notificationData = {
          ...this.newNotification,
          receiverId: Number(this.newNotification.receiverId)
        }

        addNotification(notificationData).then(response => {
          if (response.data.code === 1) {
            this.$message.success('添加成功')
            this.addDialogVisible = false
            this.resetNewNotification()
            this.fetchNotifications()
          } else {
            this.$message.error(response.data.msg || '添加失败')
          }
        }).catch(error => {
          console.error('添加通知失败', error)
          this.$message.error(error.response?.data?.msg || '添加失败')
        })
      })
    },
    showUpdateStatusDialog(id, notificationType) {
      this.updateStatusDialogVisible = true
      this.updateStatusForm.id = id
      this.updateStatusForm.notificationType = notificationType
    },
    saveUpdateStatus() {
      const { id, notificationType } = this.updateStatusForm

      if (!id || !notificationType) {
        this.$message.error('请选择通知类型')
        return
      }

      updateNotificationStatus(id, notificationType).then(response => {
        if (response.data.code === 1) {
          this.$message.success('更新成功')
          this.updateStatusDialogVisible = false
          this.fetchNotifications()
        } else {
          this.$message.error(response.data.msg || '更新失败')
        }
      }).catch(error => {
        console.error('更新通知类型失败', error)
        this.$message.error('更新失败')
      })
    },
    deleteNotification(id) {
      this.$confirm('确定删除该通知吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteNotification(id).then(response => {
          if (response.data.code === 1) {
            this.$message.success('删除成功')
            this.fetchNotifications()
          } else {
            this.$message.error(response.data.msg || '删除失败')
          }
        }).catch(error => {
          console.error('删除通知失败', error)
          this.$message.error('删除失败')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    resetNewNotification() {
      this.newNotification = {
        title: '',
        content: '',
        notificationType: null,
        senderId: null,
        receiverType: null,
        receiverId: null,
        status: 1
      }
    },
    // 处理接收者类型变化
    handleReceiverTypeChange(value) {
      console.log('接收者类型变为:', value)
      // 这里可以添加API调用获取对应类型的接收者列表
      // 例如: this.fetchReceiversByType(value)
    },
    // 格式化方法
    formatType(row) {
      const types = {
        1: '系统通知',
        2: '班级通知',
        3: '部门通知',
        4: '个人通知'
      }
      return types[row.notificationType] || row.notificationType
    },
    formatSender(row) {
      const sender = this.senderOptions.find(item => item.value === row.senderId)
      return sender ? sender.label : row.senderId
    },
    formatReceiverType(type) {
      const types = {
        1: '学生',
        2: '班级',
        3: '部门',
        4: '员工',
        5: '用户'
      }
      return types[type] || type
    },
    formatStatus(status) {
      const statusMap = {
        1: '未读',
        2: '已读',
        3: '已删除'
      }
      return statusMap[status] || status
    },
    formatDate(date) {
      if (!date) return '无记录'
      return new Date(date).toLocaleString()
    }
  }
}
</script>

<style scoped>
/* 详情标签样式 */
.detail-label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
  display: inline-block;
  min-width: 80px;
}

/* 内容框样式 */
.content-box {
  white-space: pre-line;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-top: 5px;
  line-height: 1.6;
}

/* 调整描述列表样式1 */
.el-descriptions {
  margin-top: 15px;
}

.el-descriptions-item__label {
  width: 120px;
}
</style>
